Day 8: Methods
A method is a block of code that performs a specific task. It improves code reusability and enhances readability by dividing the program into logical units. In Java, all methods must exist inside a class.
Method Definition and Invocation
A method consists of a return type, name, parameters, and body.
public class MethodBasic {
// Method with no parameters and no return value
static void greet() {
System.out.println("Hello!");
}
// Method with parameters
static void greetUser(String name) {
System.out.println(name + ", welcome!");
}
// Method with a return value
static int add(int a, int b) {
return a + b;
}
// Processing multiple values
static double calculateAverage(int[] scores) {
int sum = 0;
for (int score : scores) {
sum += score;
}
return (double) sum / scores.length;
}
public static void main(String[] args) {
greet();
greetUser("John");
int result = add(10, 20);
System.out.println("Sum: " + result);
int[] scores = {85, 90, 78, 92, 88};
double avg = calculateAverage(scores);
System.out.println("Average: " + avg);
}
}
Parameter Passing
Java always uses pass by value. For reference types, the reference value (address) is copied.
public class ParameterPassing {
// Primitive type: value is copied (original is not changed)
static void changeValue(int num) {
num = 100;
System.out.println("Inside method: " + num); // 100
}
// Reference type: reference is copied (object contents can be changed)
static void changeArray(int[] arr) {
arr[0] = 999;
System.out.println("Inside method: " + arr[0]); // 999
}
// Varargs (variable arguments)
static int sum(int... numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
public static void main(String[] args) {
// Primitive type passing
int x = 10;
changeValue(x);
System.out.println("Original: " + x); // 10 (unchanged)
// Reference type passing
int[] arr = {1, 2, 3};
changeArray(arr);
System.out.println("Original: " + arr[0]); // 999 (changed!)
// Varargs invocation
System.out.println(sum(1, 2, 3)); // 6
System.out.println(sum(10, 20, 30, 40)); // 100
System.out.println(sum()); // 0
}
}
Method Overloading
You can define multiple methods with the same name by varying the parameter types or count.
public class MethodOverloading {
// Add two integers
static int add(int a, int b) {
return a + b;
}
// Add two doubles
static double add(double a, double b) {
return a + b;
}
// Add three integers
static int add(int a, int b, int c) {
return a + b + c;
}
// Concatenate strings
static String add(String a, String b) {
return a + b;
}
// Practical example: print info methods
static void printInfo(String name) {
System.out.println("Name: " + name);
}
static void printInfo(String name, int age) {
System.out.println("Name: " + name + ", Age: " + age);
}
static void printInfo(String name, int age, String city) {
System.out.println("Name: " + name + ", Age: " + age + ", City: " + city);
}
public static void main(String[] args) {
System.out.println(add(1, 2)); // 3
System.out.println(add(1.5, 2.5)); // 4.0
System.out.println(add(1, 2, 3)); // 6
System.out.println(add("Hello", " World")); // Hello World
printInfo("John");
printInfo("John", 25);
printInfo("John", 25, "Seoul");
}
}
Recursion
A technique where a method calls itself. A termination condition (base case) is always required.
public class RecursionExample {
// Factorial: n! = n * (n-1)!
static long factorial(int n) {
if (n <= 1) return 1; // Base case
return n * factorial(n - 1);
}
// Fibonacci sequence: F(n) = F(n-1) + F(n-2)
static int fibonacci(int n) {
if (n <= 0) return 0;
if (n == 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
// Exponentiation: base^exponent
static long power(int base, int exponent) {
if (exponent == 0) return 1;
return base * power(base, exponent - 1);
}
public static void main(String[] args) {
System.out.println("5! = " + factorial(5)); // 120
System.out.println("10! = " + factorial(10)); // 3628800
System.out.print("Fibonacci: ");
for (int i = 0; i < 10; i++) {
System.out.print(fibonacci(i) + " ");
}
System.out.println(); // 0 1 1 2 3 5 8 13 21 34
System.out.println("2^10 = " + power(2, 10)); // 1024
}
}
Today’s Exercises
-
GCD Calculator: Write a method that computes the greatest common divisor of two integers using the Euclidean algorithm (recursive). Additionally, compute the least common multiple (LCM). (LCM = a * b / GCD)
-
String Utility: Implement the following methods using overloading:
repeat(String str, int count)- repeat a string count times,repeat(char ch, int count)- repeat a character count times,repeat(String str)- repeat 3 times by default. -
Array Search: Create two versions of a
searchmethod for an integer array. One performs a linear search, and the other performs a binary search (recursive) on a sorted array.